import React from 'react';
import userStyle from './index.less';
import { Avatar, Toast, Upload } from '@douyinfe/semi-ui';
import { IconCamera } from '@douyinfe/semi-icons';
import uploadFile from '@/unils/oss';
import { useModel } from 'umi';

import AuthUser from '@/api/model/users';

export default class User extends React.Component {
  constructor(props: any) {
    super(props);
  }

  render() {
    const userInfo = JSON.parse(
      window.localStorage.getItem('userinfo') as string,
    );
    return (
      <div className={userStyle.user_container}>
        <div className={userStyle.user_info_container}>
          <AvatarFn />
          <h3 className={userStyle.user_name}>{userInfo.username}</h3>
          <h3 className={userStyle.user_name}>
            {userInfo.create_time} 加入 Technique
          </h3>
        </div>
        <div className={userStyle.user_config} />
      </div>
    );
  }
}

const AvatarFn = () => {
  const { user, setuserInfo }: any = useModel(
    'user',
    (model: { user: any; setuserInfo: any }) => ({
      user: JSON.parse(window.localStorage.getItem('userinfo') as string),
      setuserInfo: model.setuserInfo,
    }),
  );
  let imageOnly = 'image/*';
  let userAvatar = '';
  const mockRequest = async ({ file }: any) => {
    const avatar = await uploadFile(file);
    const res = await AuthUser.UpdateUser({
      avatar,
    });
    if (res.status) {
      Toast.success({
        content: '更新用户信息成功',
        duration: 3,
      });
      userAvatar = avatar;
      setuserInfo({
        ...user,
        avatar,
      });
    } else {
      Toast.error({
        content: res.data.error,
        duration: 3,
      });
    }
  };

  const style = {
    backgroundColor: 'var(--semi-color-overlay-bg)',
    height: '100%',
    width: '100%',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    color: 'var(--semi-color-white)',
  };
  const hoverMask = (
    <div style={style}>
      <IconCamera />
    </div>
  );
  return (
    // @ts-ignore
    <Upload
      className="avatar-upload"
      action=""
      accept={imageOnly}
      customRequest={mockRequest}
      showUploadList={false}
      onError={() => Toast.error('上传失败')}
    >
      <Avatar
        size="extra-large"
        style={{ display: 'block', margin: '2rem 0' }}
        src={user.avatar}
        hoverMask={hoverMask}
      />
    </Upload>
  );
};
